/**
 * @Title: LoginController.java
 * @Package com.leesche.zcsp.node.controller
 * @Description:()
 * @author dennies yang
 * @date 2016年9月21日 下午2:58:12
 * @version V1.0
 */
package com.leesche.zcsp.node.web.controller.web.v2.login;

import com.leesche.zcsp.node.utils.security.QEncodeUtil;
import com.leesche.zcsp.node.utils.web.SessionManager;
import com.leesche.zcsp.node.utils.web.gernerator.CaptchaGernerator;
import com.leesche.zcsp.node.utils.web.messge.WebResult;
import com.leesche.zcsp.node.utils.web.validation.Regex;
import com.leesche.zcsp.node.web.constants.Constants;
import com.leesche.zcsp.node.web.service.SysModuleService;
import com.leesche.zcsp.node.web.service.SysUserService;
import com.leesche.zcsp.node.web.service.impl.data.read.QuerySysModuleCondition;
import com.leesche.zcsp.node.web.service.impl.data.read.QuerySysUserCondition;
import com.leesche.zcsp.node.web.service.impl.data.read.SysUserDto;
import com.leesche.zcsp.node.web.service.privilege.PrivilegeService;
import com.leesche.zcsp.node.web.vo.Account;
import com.leesche.zcsp.node.web.vo.Principal;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author dennies yang
 * @version V1.0
 * @Title: LoginController.java
 * @Package com.leesche.zcsp.node.controller
 * @Description:(登录界面)
 * @date 2016年9月21日 下午3:02:45
 */
@Controller
@RequestMapping(value = "/v2")
public class WebLoginController {

    private final Logger logger = Logger.getLogger(WebLoginController.class);

    private static final String LOGIN_VIEW = "web/v2/login/signin";
    private static final String FACTORYLOGIN_VIEW = "web/v2/login/factorysignin";

    @Autowired
    private PrivilegeService privilegeService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysModuleService sysModuleService;

    @RequestMapping(value = {"/login"})
    public String showLoginView() {
        return LOGIN_VIEW;
    }

    @RequestMapping(value = {"/factorylogin"})
    public String showFactoryLoginView() {
        return FACTORYLOGIN_VIEW;
    }

    /**
     * @param account 登录的账户
     * @Title: login(Account account)
     * @Description: TODO(PC端用户登录入口)
     * @author Jerry
     * @date 2016-10-15 12:44:49
     */
    @ResponseBody
    @RequestMapping(value = "/signin", method = RequestMethod.POST)
    public Map<String, Object> login(Account account) {
        try {

            if (!SessionManager.getSessionAttribute(Constants.LOGIN_CODE).equals(account.getVildCode())) {
                return WebResult.failure("验证码输入错误").toMap();
            }

            List<SysUserDto> users = this.getUserInfo(account.getUsername());
            if (users == null || users.size() <= 0) {
                return WebResult.failure("用户名/手机号不存在，请重新输入").toMap();
            } else if (users.size() > 1) {
                return WebResult.failure("账户冲突，请与管理员联系").toMap();
            } else {
                SysUserDto user = users.get(0);
                if (user == null) {
                    return WebResult.failure("用户名/手机号不存在，请重新输入").toMap();
                } else if (user.getState() == 2) {
                    return WebResult.failure("您的账户已暂停使用，如需开放请与管理员联系").toMap();
                }

                int type = user.getNtype();
                // 4 表示娱乐城老板
                // 0、5、6、7 表示娱乐城老板自定义的子角色
                if (type != 4 && type != 5 && type != 6 && type != 7 && type != 8) {
                    return WebResult.failure("您的帐号，不能登录商户系统").toMap();
                } else {
                    Map<String, Object> resultMap = this.webLogin(user, account.getPassword());
                    if (Boolean.parseBoolean(resultMap.get("result").toString())) {
                        SessionManager.setSessionAttribute("username", privilegeService.getCurrentPrincipal().getBusinessno());
                    }
                    return resultMap;
                }
            }

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }


    /**
     * @param account 登录的账户
     * @Title: login(Account account)
     * @Description: TODO(PC端用户登录入口)
     * @author Jerry
     * @date 2016-10-15 12:44:49
     */
    @ResponseBody
    @RequestMapping(value = "/factorysignin", method = RequestMethod.POST)
    public Map<String, Object> factoryLogin(Account account,HttpSession session) {
        try {

            if (!session.getAttribute(Constants.LOGIN_CODE).equals(account.getVildCode())) {
                return WebResult.failure("验证码输入错误").toMap();
            }

            //SysUser user = this.getUserInfo(account.getUsername());

            List<SysUserDto> users = this.getUserInfo(account.getUsername());

            if (users == null || users.size() <= 0) {
                return WebResult.failure("用户名/手机号不存在，请重新输入").toMap();
            } else if (users.size() > 1) {
                return WebResult.failure("账户冲突，请与管理员联系").toMap();
            } else {

                SysUserDto user = users.get(0);
                if (user == null) {
                    return WebResult.failure("用户名/手机号不存在，请重新输入").toMap();
                } else if (user.getState() == 2) {
                    return WebResult.failure("您的账户已暂停使用，如需开放请与管理员联系").toMap();
                }
                Integer type = user.getNtype();
                // 2 表示工厂用户 、3 表示工厂子用户
                if (type != 2 && type != 3) {
                    return WebResult.failure("您非管理用户，不能登录管理系统").toMap();
                } else {
                    Map<String, Object> resultMap = this.webLogin(user, account.getPassword());
                    if (Boolean.parseBoolean(resultMap.get("result").toString())) {
                        SessionManager.setSessionAttribute("username", privilegeService.getCurrentPrincipal().getUsername());
                        SessionManager.setSessionAttribute("businessno", privilegeService.getCurrentPrincipal().getBusinessno());
                    }
                    return resultMap;
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }


    /**
     * @return SysUser
     * @Title: getUserInfo(String username)
     * @Description: TODO(根据用户名获取用户信息)
     * @author Jerry Chan
     * @date 2017/1/11 19:34
     */
    private List<SysUserDto> getUserInfo(String username) {

        QuerySysUserCondition condition = new QuerySysUserCondition();
        if (Regex.isEmail(username)) {
            condition.setEmail(username);
        } else if (Regex.isMobile(username)) {
            condition.setMobile(username);
        } else {
            condition.setUsername(username);
        }

        return sysUserService.findListsByCondition(condition);

        //根据用户的账户名获取用户信息
        /*sysUser = sysUserService.findUserByUsername(sysUser);
        return sysUser != null ? sysUser : null;*/

    }

    /**
     * @return
     * @Title: webLogin(Account account)
     * @Description: TODO(工厂用户、娱乐城老板、子账户登录入口)
     * @author Jerry Chan
     * @date 2017/1/11 19:21
     */
    private Map<String, Object> webLogin(SysUserDto sysUser, String password) throws Exception {

        if (sysUser != null) {
            if (sysUser.getPassword().equals(QEncodeUtil.md5Encrypt(password))) {

                QuerySysModuleCondition querySysModuleCondition = new QuerySysModuleCondition();
                querySysModuleCondition.setnType(Constants.MODULE_TYPE_WEB);
                querySysModuleCondition.setUserId(sysUser.getUserid());

                Principal principal = new Principal();
                principal.setUserid(sysUser.getUserid());
                principal.setParentid(sysUser.getPuserid());
                principal.setBusinessno(sysUser.getBusinessno());
                principal.setUsername(sysUser.getUsername());
                principal.setNtype(sysUser.getNtype());
                principal.setOpenId(sysUser.getOpenid());
                principal.setUserShortCode(sysUser.getShortcode());
                principal.setModuleIds(sysModuleService.findModuleIDbyUserID(querySysModuleCondition));

                SessionManager.setSessionAttribute(Constants.LOGIN_CURRENT_USER, principal);

                return WebResult.success().put("type", sysUser.getNtype()).toMap();
            }
            return WebResult.failure("登录密码错误，请重新输入").toMap();
        } else {
            return WebResult.failure("用户名/手机号不存，请重新输入").toMap();
        }

    }


    /**
     * @Title: quit()
     * @Description: TODO(PC端用户登出入口)
     * @author Jerry
     * @date 2016-10-15 12:44:49
     */
    @ResponseBody
    @RequestMapping(value = "/signout", method = RequestMethod.DELETE)
    public Map<String, Object> quit() {
        try {
            if (privilegeService.getCurrentPrincipal() != null) {
                SessionManager.destroySession();
                return WebResult.success().toMap();
            } else {
                return WebResult.failure("用户未登录，请先登录").toMap();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * @Title: getAuthCode @Description: TODO(验证码) @param @param request @param @param
     * response @param @param session @param @throws IOException @return
     * void @throws
     */
    @RequestMapping({"authCode"})
    public void getAuthCode(HttpServletRequest request,
                            HttpServletResponse response, HttpSession session)
            throws IOException {
        // 设置response头信息
        // 禁止缓存
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        // 将字符保存到session中用于前端的验证
        session.setAttribute(Constants.LOGIN_CODE,
                CaptchaGernerator.ImageGernerator(response.getOutputStream()));

    }

}
